{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T18:57:30.986002Z",
     "start_time": "2019-01-11T18:57:30.840046Z"
    }
   },
   "outputs": [],
   "source": [
    "%reload_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Reading Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T20:02:53.098902Z",
     "start_time": "2019-01-11T20:02:52.292083Z"
    },
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((7628, 2), (2748, 1), (2748, 1))"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train = pd.read_excel('Data_Train.xlsx')\n",
    "test = pd.read_excel('Data_Test.xlsx')\n",
    "sub = pd.read_excel('Sample_submission.xlsx')\n",
    "\n",
    "train.shape, test.shape, sub.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Data PreProcessing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "import itertools\n",
    "def remove_noise(text):\n",
    "    # Make lowercase\n",
    "    text = text.apply(lambda x: \" \".join(x.lower() for x in x.split()))\n",
    "    \n",
    "    # Remove whitespaces\n",
    "    text = text.apply(lambda x: \" \".join(x.strip() for x in x.split()))\n",
    "    \n",
    "    # Convert to string\n",
    "    text = text.astype(str)\n",
    "        \n",
    "    return text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "train['STORY'] = remove_noise(train['STORY'])\n",
    "test['STORY'] = remove_noise(test['STORY'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Feature Engineering"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T20:06:13.634632Z",
     "start_time": "2019-01-11T20:06:13.471639Z"
    }
   },
   "outputs": [],
   "source": [
    "from nltk.tokenize import WordPunctTokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T20:06:13.634632Z",
     "start_time": "2019-01-11T20:06:13.471639Z"
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "tt = WordPunctTokenizer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T20:02:58.453558Z",
     "start_time": "2019-01-11T20:02:54.528843Z"
    }
   },
   "outputs": [],
   "source": [
    "cv = CountVectorizer(tokenizer=tt.tokenize, stop_words='english', ngram_range=(1,3))\n",
    "\n",
    "cv.fit(train.STORY.tolist() + test.STORY.tolist())\n",
    "train_cv = cv.transform(train.STORY)\n",
    "test_cv = cv.transform(test.STORY)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "tf_idf = TfidfVectorizer(min_df=3,  max_features=None, \n",
    "            strip_accents='unicode', analyzer='word', token_pattern=r'\\w{1,}',\n",
    "            ngram_range=(1, 3), use_idf=1.0,smooth_idf=1.0,sublinear_tf=1.0,\n",
    "            stop_words = 'english')\n",
    "\n",
    "tf_idf.fit(train.STORY.tolist() + test.STORY.tolist())\n",
    "train_tf = tf_idf.transform(train.STORY)\n",
    "test_tf = tf_idf.transform(test.STORY)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Modeling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression, LogisticRegressionCV\n",
    "from sklearn.naive_bayes import MultinomialNB, BernoulliNB\n",
    "from sklearn.svm import SVC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T20:04:15.560149Z",
     "start_time": "2019-01-11T20:04:11.675892Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/abdulqam/.conda/envs/python3/lib/python3.6/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n",
      "  FutureWarning)\n",
      "/Users/abdulqam/.conda/envs/python3/lib/python3.6/site-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n",
      "  FutureWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2min, sys: 6.17 s, total: 2min 6s\n",
      "Wall time: 1min 29s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "best_params = {'C': 0.9, 'max_iter': 100, 'multi_class': 'ovr', 'penalty': 'l2'}\n",
    "m = LogisticRegression(**best_params, class_weight='balanced')\n",
    "m.fit(train_cv, train.SECTION)\n",
    "\n",
    "best_params = {'alpha': 0.5}\n",
    "nb = MultinomialNB(**best_params)\n",
    "nb.fit(train_cv, train.SECTION)\n",
    "\n",
    "best_params = {'alpha': 5e-08}\n",
    "nb2 = BernoulliNB(**best_params)\n",
    "nb2.fit(train_cv, train.SECTION)\n",
    "\n",
    "best_params = {'C': 250, 'max_iter': 100, 'multi_class': 'ovr', 'penalty': 'l2'}\n",
    "m_tf = LogisticRegression(**best_params, class_weight='balanced')\n",
    "m_tf.fit(train_tf, train.SECTION)\n",
    "\n",
    "best_params = {'alpha': 0.06}\n",
    "nb_tf = MultinomialNB(**best_params)\n",
    "nb_tf.fit(train_tf, train.SECTION)\n",
    "\n",
    "best_params = {'kernel': 'linear', 'C': 1}\n",
    "svc_tf = SVC(**best_params, class_weight='balanced', probability=True)\n",
    "svc_tf.fit(train_tf, train.SECTION)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Ensembing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T20:04:18.479020Z",
     "start_time": "2019-01-11T20:04:18.256218Z"
    }
   },
   "outputs": [],
   "source": [
    "from scipy.stats.mstats import mode\n",
    "\n",
    "pred1 = m.predict_proba(test_cv)\n",
    "pred2 = nb.predict_proba(test_cv)\n",
    "pred3 = nb2.predict_proba(test_cv)\n",
    "pred4 = m_tf.predict_proba(test_tf)\n",
    "pred5 = nb_tf.predict_proba(test_tf)\n",
    "pred6 = svc_tf.predict_proba(test_tf)\n",
    "\n",
    "test_pred_prob = np.mean([pred1, pred2, pred3, pred4, pred5, pred6], axis=0)\n",
    "pred = np.argmax(test_pred_prob, axis=1)\n",
    "# from sklearn.metrics import accuracy_score\n",
    "# accuracy_score(test.SECTION, pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-01-11T20:04:33.816643Z",
     "start_time": "2019-01-11T20:04:33.435606Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>SECTION</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   SECTION\n",
       "0        1\n",
       "1        2\n",
       "2        1\n",
       "3        0\n",
       "4        1"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "submission = pd.DataFrame()\n",
    "submission['SECTION'] = pred.astype(int)\n",
    "submission.to_excel(\"ml_prob.xlsx\", index=None)\n",
    "submission.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
